<?php
use Illuminate\Support\Facades\Input;
class ProductController extends RestrictedBaseController {
	
	public function index() {
		$this->layout->content = View::make('product.index');
	}
	
	public function getList() {
		$this->layout = null;
	
		$query = Product::select()->with('components')->orderBy('name');
		$pName = Input::get('name');
	
		if (!empty($pName)) {
			$query->where('name', 'like', '%' . $pName . '%');
		}
	
		return Datatables::of($query)->make(true);
	}
	
	public function create($fromId = null) {
		$this->layout->content = View::make('product.create')
			->with('privileges', Privilege::all())
			->with('costsCentres', CostsCentre::orderBy('id')->get()->toJson())
			->with('inputAccessories', Input::old('accessories'))
			->with('inputCigamCodes', Input::old('cigamCodes'))
			->with('inputComponents', Input::old('components'))
			->with('inputCostCentres', Input::old('costCentres'))
			->with('inputAmounts', Input::old('amounts'));
		
		if (!empty($fromId)) {
			$this->layout->content
				->with('productComponents', ProductComponent::whereProductWithComponents($fromId)->get());
		}
	}
	
	public function store() {
		$rules = Product::$rules;
		unset($rules['currentAccessories'], $rules['currentCostsCentres'], $rules['currentAmounts']);
		$validator = Validator::make(Input::all(), $rules);
		
		if ($validator->fails()) {
			return Redirect::to('product/create')
				->withErrors($validator)
				->withInput(Input::all());
		} else {
			DB::transaction(function() {
				$product = new Product();
				$product->name = Input::get('name');
				$product->user_id = Auth::user()->id;
				$product->save();
					
				foreach (Input::get('components') as $key => $componentName) {
					$component = Component::where('name', '=', $componentName)->where('code', '=', Input::get('cigamCodes')[$key])->first();
				
					if (empty($component)) {
						$component = new Component();
						$component->accessory = Input::get('accessories')[$key];
						$component->code = Input::get('cigamCodes')[$key];
						$component->name = $componentName;
						$component->user_id = Auth::user()->id;
						$component->save();
					}
				
					$productComponent = new ProductComponent();
					$productComponent->product_id = $product->id;
					$productComponent->component_id = $component->id;
					$productComponent->amount = Input::get('amounts')[$key];
					$productComponent->save();
					
					$component->costsCentres()->detach();
					$costsCentres = explode(",", Input::get('costCentres')[$key]);

					foreach ($costsCentres as $key => $costCentre) {
						$componentCostCentre = new ComponentCostCentre();
						$componentCostCentre->component_id = $component->id;
						$componentCostCentre->costs_centre_id = $costCentre;
						$componentCostCentre->step = $key + 1;
						$componentCostCentre->user_id = Auth::user()->id;
						$componentCostCentre->save();
					}
				}
			});
				
			Session::flash('message', 'Item de catálogo incluído com sucesso');
			return Redirect::to('product');
		}
	}
	
	public function edit($id) {
		$product = Product::find($id);
		
		$this->layout->content = View::make('product.edit')
			->with('product', $product)
			->with('costsCentres', CostsCentre::orderBy('id')->get()->toJson())
			->with('productComponents', ProductComponent::whereProductWithComponents($id)->get())
			->with('inputAccessories', Input::old('accessories'))
			->with('inputCigamCodes', Input::old('cigamCodes'))
			->with('inputComponents', Input::old('components'))
			->with('inputCostCentres', Input::old('costCentres'))
			->with('inputAmounts', Input::old('amounts'));
	}
	
	public function update($id) {
		$rules = Product::$rules;
		$rules['name'] = $rules['name'] . ',name,' . $id;

		$pComponents = Input::get('components');
		$pCurrentComponents = Input::get('currentComponents');

		if (!empty($pCurrentComponents) && empty($pComponents)) {
			unset($rules['accessories'], $rules['cigamCodes'], $rules['components'], $rules['costCentres'], $rules['amounts']);
		}

		if (empty($pCurrentComponents)) {
			unset($rules['currentAccessories'], $rules['currentCostsCentres'], $rules['currentAmounts']);
		}
		
		$validator = Validator::make(Input::all(), $rules);
	
		if ($validator->fails()) {
			return Redirect::to("product/{$id}/edit")
				->withErrors($validator)
				->withInput(Input::all());
		} else {
			DB::transaction(function() use ($id, $pComponents) {
				$product = Product::find($id);
				$product->name = Input::get('name');
				$product->user_id = Auth::user()->id;
				$product->save();
				
				$inputCurrentComponents = Input::get('currentComponents');
				$inputNewComponents = empty($pComponents) ? array() : $pComponents;
				$componentList = array();
				
				// componentes existentes
				if (!empty($inputCurrentComponents)) {
					foreach ($inputCurrentComponents as $key => $componentName) {
						$currentComponent = Component::find($key);
						
						if ($currentComponent->name != $componentName 
								|| $currentComponent->code != Input::get('currentCigamCodes')[$key] 
								|| $currentComponent->accessory != Input::get('currentAccessories')[$key] ) {
							if ($currentComponent->isEditable()) {
								// nome alterado pode ja existir
								$component = Component::where('id', '<>', $key)
															->where('name', '=', $componentName)
															->where('code', '=', Input::get('currentCigamCodes')[$key])
															->first();
								
								if (empty($component)) {
									//edita o atual
									$currentComponent->accessory = Input::get('currentAccessories')[$key];
									$currentComponent->code = Input::get('currentCigamCodes')[$key];
									$currentComponent->name = $componentName;
									$currentComponent->save();
								
									array_push($componentList, array('id' => $key, 'amount' => Input::get('currentAmounts')[$key]));
								} else {
									// reutiliza o componente encontrado, atualizando informações sensíveis à alterações
									$component->accessory = Input::get('currentAccessories')[$key];
									$component->save();
									
									array_push($componentList, array('id' => $component->id, 'amount' => Input::get('currentAmounts')[$key]));
								}
							} else {
								$replacingComponent = Component::where('name', '=', $componentName)
									->where('code', '=', Input::get('currentCigamCodes')[$key])
									->first();
								
								if (empty($replacingComponent)) {
									$replacingComponent = new Component();
									$replacingComponent->accessory = Input::get('currentAccessories')[$key];
									$replacingComponent->code = Input::get('currentCigamCodes')[$key];
									$replacingComponent->name = $componentName;
									$replacingComponent->user_id = Auth::user()->id;
									$replacingComponent->save();
								}

								$replacingComponent->costsCentres()->detach();
								$replacingCostCentres = explode(",", Input::get('currentCostsCentres')[$key]);
								
								if (!empty($replacingCostCentres)) {
									foreach ($replacingCostCentres as $keyAux => $costCentre) {
										$componentCostCentre = new ComponentCostCentre();
										$componentCostCentre->component_id = $replacingComponent->id;
										$componentCostCentre->costs_centre_id = $costCentre;
										$componentCostCentre->step = $keyAux + 1;
										$componentCostCentre->user_id = Auth::user()->id;
										$componentCostCentre->save();
									}
								}
								
								array_push($componentList, array('id' => $replacingComponent->id, 'amount' => Input::get('currentAmounts')[$key]));
								
								continue;
							}
						} else {
							array_push($componentList, array('id' => $currentComponent->id, 'amount' => Input::get('currentAmounts')[$key]));
						}
						
						$currentComponent->costsCentres()->detach();
						$costsCentres = explode(",", Input::get('currentCostsCentres')[$key]);
						$step = 1;
						
						foreach ($costsCentres as $key => $costCentre) {
							$componentCostCentre = new ComponentCostCentre();
							$componentCostCentre->component_id = $currentComponent->id;
							$componentCostCentre->costs_centre_id = $costCentre;
							$componentCostCentre->step = $step;
							$componentCostCentre->user_id = Auth::user()->id;
							$componentCostCentre->save();
							
							$step++;
						}
					}
				}
				
				// novos componentes
				if (!empty($inputNewComponents)) {					
					foreach ($inputNewComponents as $key => $componentName) {
						$component = Component::where('name', '=', $componentName)->where('code', '=', Input::get('cigamCodes')[$key])->first();
							
						if (empty($component)) {
							$component = new Component();
							$component->accessory = Input::get('accessories')[$key];
							$component->code = Input::get('cigamCodes')[$key];
							$component->name = $componentName;
							$component->user_id = Auth::user()->id;
							$component->save();
						}
				
						$component->costsCentres()->detach();
						$costCentres = explode(",", Input::get('costCentres')[$key]);
						
						if (!empty($costCentres)) {
							foreach ($costCentres as $keyCC => $costCentre) {
								$componentCostCentre = new ComponentCostCentre();
								$componentCostCentre->component_id = $component->id;
								$componentCostCentre->costs_centre_id = $costCentre;
								$componentCostCentre->step = $keyCC + 1;
								$componentCostCentre->user_id = Auth::user()->id;
								$componentCostCentre->save();
							}
						}
						
						array_push($componentList, array('id' => $component->id, 'amount' => Input::get('amounts')[$key]));
					}
				}
				
				$product->components()->detach();
				foreach ($componentList as $cObj) {
					$productComponent = new ProductComponent();
					$productComponent->product_id = $id;
					$productComponent->component_id = $cObj['id'];
					$productComponent->amount = $cObj['amount'];
					$productComponent->save();
				}
			});
			
			Session::flash('message', 'Item de catálogo atualizado com sucesso');
			return Redirect::to('product');
		}
	}
	
	public function getComponentsSuggestions() {
		$this->layout = null;
		$suggestions = Component::where('name', 'like', '%' . Input::get('term') . '%')
									->with('costsCentres')
									->orderBy('code')->orderBy('name')
									->get();
	
		return Response::json($suggestions);
	}

	public function postRetrieveComponents() {
		$this->layout = null;
		$productComponents = Product::find(Input::get('id'))->components()->with('costsCentres')->get(['id', 'accessory', 'code', 'name', 'amount']);
	
		return Response::json($productComponents);
	}
	
	public function destroy($id) {
		$product = Product::find($id);
		$product->components()->detach();
		$product->delete();
	
		Session::flash('message', 'Item do catálogo excluído com sucesso');
		return Redirect::to('product');
	}
	
}